import 'dart:convert' as convert;
import 'dart:io';

import 'package:file_picker/file_picker.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:path_provider/path_provider.dart';
import 'package:realmega_ota/realmega/setting_and_filter_manager.dart';
import 'package:realmega_ota/util/ios_compat.dart';

import '../constants.dart';
import '../util/log_util.dart';
import '../util/util.dart';

class SettingAndFilterWidget extends StatefulWidget{

  final SettingInfoCallback onSettingInfoCallback;
  final FilterInfoCallback onFilterInfoCallback;

  const SettingAndFilterWidget({super.key, required this.onSettingInfoCallback, required this.onFilterInfoCallback});

  @override
  State<StatefulWidget> createState() {
    return _SettingAndFilterState();
  }

}

class _SettingAndFilterState extends State<SettingAndFilterWidget>{

  bool _isExpanded = false;

  @override
  void initState() {
    super.initState();
    SettingAndFilterManager.instance.getFilterWordsFromFile().then((value) {
      _addressFilter = value.putIfAbsent('addressFilter', () => '');
      _advNameFilter = value.putIfAbsent('advNameFilter', () => '');
      SettingAndFilterManager.instance.advNameFilter = _advNameFilter;
      SettingAndFilterManager.instance.addressFilter = _addressFilter;
      //读取到数据后设置数据更新UI
      setState(() {

      });
    });

    SettingAndFilterManager.instance.getOtaWordsFromFile().then((map) async {
      _filePath = map.putIfAbsent('filePath', () => '');
      _isVersionCheck = map.putIfAbsent('isVersionCheck', () => false);
      _macCode = map.putIfAbsent('macCode', () => '8899AABBCCDDEEFF');
      _creditCode = map.putIfAbsent('creditCode', () => '524d4943');
      _isBondCheck = map.putIfAbsent('isBondCheck', () => true);

      if(_filePath.isNotEmpty && Platform.isIOS){
        // Directory? documentsDir = await getApplicationDocumentsDirectory();
        // String fileName = _filePath.split('/').last;
        // _filePath = documentsDir.path + '/' + fileName;
        _filePath = await replaceUid(_filePath);
      }

      SettingAndFilterManager.instance.filePath = _filePath;
      SettingAndFilterManager.instance.isVersionCheck = _isVersionCheck;
      SettingAndFilterManager.instance.macCode = _macCode;
      SettingAndFilterManager.instance.creditCode = _creditCode;
      SettingAndFilterManager.instance.isBondCheck = _isBondCheck;
      //读取到数据后设置数据更新UI
      setState(() {

      });
    });
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return ExpansionTile(
      title: Text("Setting And Filter"),
      // leading: Text('rssi: ${result.rssi.toString()}'),
      trailing: Icon(_isExpanded ? Icons.keyboard_arrow_up_rounded : Icons.keyboard_arrow_down_rounded),
      initiallyExpanded: _isExpanded,
      onExpansionChanged: (isExpansion){
        setState(() {
          _isExpanded = isExpansion;
        });
      },
      children: <Widget>[
        _buildOtaSetting(),
        Container(height: 10,),
        _buildAddressFilter(),
        Container(height: 10,),
        _buildAdvNameFilter(),
        Container(height: 10,),
        _buildMacFilter(),
        Container(height: 10,),
        _buildFixedCredit(),
        Container(height: 10,),
        _buildVersionCheck(),
        // Container(height: 10,),
        // _buildBondCheck(),
        // _buildDivider(),
        // _buildSearchBtn(),
      ],
    );
  }

  final double _filter_label_width = 120;

  String _addressFilter = '';
  _buildAddressFilter(){
    return Row(
      children: [
        Container(width: COMMON_MARGIN_LENGTH,),
        Container(width: _filter_label_width, child: Text('Address Filter:')),
        Expanded(child: TextField(
          autofocus: false,
          controller: TextEditingController.fromValue(TextEditingValue(
            // 设置内容
              text: _addressFilter,
              // 保持光标在最后
              selection: TextSelection.fromPosition(TextPosition(
                  affinity: TextAffinity.downstream,
                  offset: _addressFilter.length)))),
          textInputAction: TextInputAction.done,
          textAlignVertical: TextAlignVertical.center,
          onChanged: (value){
            // Log.d('onChanged:$value');
            setState(() {
              _addressFilter = value;
              SettingAndFilterManager.instance.addressFilter = _addressFilter;
              // writeSearchWordsToFile(_searchTxt);
            });
          },
          decoration: const InputDecoration(
            fillColor: Color(0x30cccccc),
            filled: true,
            enabledBorder: OutlineInputBorder(
                borderSide: BorderSide(color: Color(0x00FF0000)),
                borderRadius: BorderRadius.all(Radius.circular(4))),
            hintText: 'Please input filter text',
            hintStyle: TextStyle(
                height: 1.4, fontSize: 14, color: Colors.black26),
            contentPadding: EdgeInsets.only(left: 15, top: 10),
            focusedBorder: OutlineInputBorder(
                borderSide: BorderSide(color: Color(0x00000000)),
                borderRadius: BorderRadius.all(Radius.circular(4))),
          ),
        )),
        Container(width: COMMON_MARGIN_LENGTH,)
      ],
    );
  }

  String _advNameFilter = '';
  _buildAdvNameFilter(){
    return Row(
      children: [
        Container(width: COMMON_MARGIN_LENGTH,),
        Container(width: _filter_label_width, child: Text('Adv Name Filter:')),
        Expanded(child: TextField(
          autofocus: false,
          controller: TextEditingController.fromValue(TextEditingValue(
            // 设置内容
              text: _advNameFilter,
              // 保持光标在最后
              selection: TextSelection.fromPosition(TextPosition(
                  affinity: TextAffinity.downstream,
                  offset: _advNameFilter.length)))),
          textInputAction: TextInputAction.done,
          textAlignVertical: TextAlignVertical.center,
          onChanged: (value){
            // Log.d('onChanged:$value');
            setState(() {
              _advNameFilter = value;
              SettingAndFilterManager.instance.advNameFilter = _advNameFilter;
              // writeSearchWordsToFile(_searchTxt);
            });
          },
          decoration: const InputDecoration(
            fillColor: Color(0x30cccccc),
            filled: true,
            enabledBorder: OutlineInputBorder(
                borderSide: BorderSide(color: Color(0x00FF0000)),
                borderRadius: BorderRadius.all(Radius.circular(4))),
            hintText: 'Please input filter text',
            hintStyle: TextStyle(
                height: 1.4, fontSize: 14, color: Colors.black26),
            contentPadding: EdgeInsets.only(left: 15, top: 10),
            focusedBorder: OutlineInputBorder(
                borderSide: BorderSide(color: Color(0x00000000)),
                borderRadius: BorderRadius.all(Radius.circular(4))),
          ),
        )),
        Container(width: COMMON_MARGIN_LENGTH,)
      ],
    );
  }


  String _macCode = '8899AABBCCDDEEFF';
  _buildMacFilter(){
    return Row(
      children: [
        Container(width: COMMON_MARGIN_LENGTH,),
        Container(width: _filter_label_width, child: Text('Mac:')),
        Expanded(child: TextField(
          autofocus: false,
          controller: TextEditingController.fromValue(TextEditingValue(
            // 设置内容
              text: _macCode,
              // 保持光标在最后
              selection: TextSelection.fromPosition(TextPosition(
                  affinity: TextAffinity.downstream,
                  offset: _macCode.length)))),
          textInputAction: TextInputAction.done,
          textAlignVertical: TextAlignVertical.center,
          onChanged: (value){
            // Log.d('onChanged:$value');
            setState(() {
              _macCode = value;
              SettingAndFilterManager.instance.macCode = _macCode;
              // writeSearchWordsToFile(_searchTxt);
              if(!isHexString(_macCode)){
                Fluttertoast.showToast(msg: 'macCode输入只能在0~F之间');
              }
            });
          },
          decoration: const InputDecoration(
            fillColor: Color(0x30cccccc),
            filled: true,
            enabledBorder: OutlineInputBorder(
                borderSide: BorderSide(color: Color(0x00FF0000)),
                borderRadius: BorderRadius.all(Radius.circular(4))),
            hintText: 'Please input mac code',
            hintStyle: TextStyle(
                height: 1.4, fontSize: 14, color: Colors.black26),
            contentPadding: EdgeInsets.only(left: 15, top: 10),
            focusedBorder: OutlineInputBorder(
                borderSide: BorderSide(color: Color(0x00000000)),
                borderRadius: BorderRadius.all(Radius.circular(4))),
          ),
        )),
        Container(width: COMMON_MARGIN_LENGTH,)
      ],
    );
  }

  String _creditCode = '524d4943';
  _buildFixedCredit(){
    return Row(
      children: [
        Container(width: COMMON_MARGIN_LENGTH,),
        Container(width: _filter_label_width, child: Text('Fixed Credit:')),
        Expanded(child: TextField(
          autofocus: false,
          controller: TextEditingController.fromValue(TextEditingValue(
            // 设置内容
              text: _creditCode,
              // 保持光标在最后
              selection: TextSelection.fromPosition(TextPosition(
                  affinity: TextAffinity.downstream,
                  offset: _creditCode.length)))),
          textInputAction: TextInputAction.done,
          textAlignVertical: TextAlignVertical.center,
          onChanged: (value){
            // Log.d('onChanged:$value');
            setState(() {
              _creditCode = value;
              SettingAndFilterManager.instance.creditCode = _creditCode;
              // writeSearchWordsToFile(_searchTxt);
              if(!isHexString(_creditCode)){
                Fluttertoast.showToast(msg: 'creditCode只能在0~F之间');
              }
            });
          },
          decoration: const InputDecoration(
            fillColor: Color(0x30cccccc),
            filled: true,
            enabledBorder: OutlineInputBorder(
                borderSide: BorderSide(color: Color(0x00FF0000)),
                borderRadius: BorderRadius.all(Radius.circular(4))),
            hintText: 'Please input credit code',
            hintStyle: TextStyle(
                height: 1.4, fontSize: 14, color: Colors.black26),
            contentPadding: EdgeInsets.only(left: 15, top: 10),
            focusedBorder: OutlineInputBorder(
                borderSide: BorderSide(color: Color(0x00000000)),
                borderRadius: BorderRadius.all(Radius.circular(4))),
          ),
        )),
        Container(width: COMMON_MARGIN_LENGTH,)
      ],
    );
  }

  bool _isVersionCheck = false;
  _buildVersionCheck(){
    return Row(
      children: [
        Container(width: 5,),
        Checkbox(value: _isVersionCheck, onChanged: (checked){
          setState(() {
            _isVersionCheck = checked!;
            // Log.d('$_isVersionCheck, $_filePath, $_advNameFilter, $_addressFilter, $_macCode, $_creditCode');
            SettingAndFilterManager.instance.isVersionCheck = _isVersionCheck;
          });
        }),
        Text('Check Software Version'),
      ],
    );
  }

  bool _isBondCheck = true;
  _buildBondCheck(){
    return Row(
      children: [
        Container(width: 5,),
        Checkbox(value: _isBondCheck, onChanged: (checked){
          setState(() {
            _isBondCheck = checked!;
            SettingAndFilterManager.instance.isBondCheck = _isBondCheck;
          });
        }),
        const Text('Check Pair'),
      ],
    );
  }

  _buildDivider(){
    return const Divider(thickness: 1,indent: COMMON_MARGIN_LENGTH);
  }

  String _filePath = '';
  _buildOtaSetting(){
    return Column(
      mainAxisAlignment: MainAxisAlignment.start,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          children: [
            Container(width: COMMON_MARGIN_LENGTH,),
            Container(width: _filter_label_width, child: Text('Ota Image File:')),
            Expanded(child: TextField(
              autofocus: false,
              controller: TextEditingController.fromValue(TextEditingValue(
                // 设置内容
                  text: _filePath,
                  // 保持光标在最后
                  selection: TextSelection.fromPosition(TextPosition(
                      affinity: TextAffinity.downstream,
                      offset: _filePath.length)))),
              textInputAction: TextInputAction.done,
              textAlignVertical: TextAlignVertical.center,
              onChanged: (value){
                // Log.d('onChanged:$value');
                setState(() {
                  _filePath = value;
                  // writeSearchWordsToFile(_searchTxt);
                });
              },
              decoration: const InputDecoration(
                fillColor: Color(0x30cccccc),
                filled: true,
                enabledBorder: OutlineInputBorder(
                    borderSide: BorderSide(color: Color(0x00FF0000)),
                    borderRadius: BorderRadius.all(Radius.circular(4))),
                hintText: 'Please select ota file',
                hintStyle: TextStyle(
                    height: 1.4, fontSize: 14, color: Colors.black26),
                contentPadding: EdgeInsets.only(left: 15, top: 10),
                focusedBorder: OutlineInputBorder(
                    borderSide: BorderSide(color: Color(0x00000000)),
                    borderRadius: BorderRadius.all(Radius.circular(4))),
              ),
            )),
            IconButton(onPressed: (){
              _pickOtaFile();
            }, icon: const Icon(Icons.file_upload)),
            Container(width: COMMON_MARGIN_LENGTH,)
          ],
        ),
        Container(
          margin: const EdgeInsets.only(left: 140),
          child: const Text('注意：不同升级文件不能用相同文件名称', style: TextStyle(fontSize: 12,color: Colors.black26),),
        ),
      ],
    );
  }

  _buildSearchBtn(){
    return ElevatedButton(onPressed: (){
      widget.onFilterInfoCallback(_addressFilter, _advNameFilter);
    }, child: Text('Search'));
  }




  Future<void> _pickOtaFile() async {
    Log.d('选择升级文件');
    FilePicker.platform.pickFiles().then((result) async {
      if (result != null) {
        Log.d('选择文件：$result');
        if(Platform.isIOS){
          _filePath = await _copyFileToDoc(result.files.single.path!);
        }else {
          _filePath = result.files.single.path!;
        }

        SettingAndFilterManager.instance.filePath = _filePath;

        if(mounted) {
          setState(() {

          });
        }
      }else{
        Log.d('没有选择文件');
      }
    }).onError((error, stackTrace) {
      Log.d('选择文件报错:$stackTrace');
    }).catchError((onError){
      Log.d('选择文件异常：$onError');
    });
    // FilePickerResult? result = await FilePicker.platform.pickFiles();


    //else {
    //Fluttertoast.showToast(msg: "请选择OTA升级文件");
    //}
  }

  Future<String> _copyFileToDoc(String path) async {
    String fileName = path.split('/').last;
    File file = File(path);
    Directory? documentsDir = await getApplicationDocumentsDirectory();

    File dstFile = file.renameSync('${documentsDir.path}/$fileName');
    Log.d('dstFile:${dstFile.path} is exists:${dstFile.existsSync()}');
    return dstFile.path;
  }
}

typedef SettingInfoCallback = void Function(String filePath, String mac, bool isVersionCheck, String creditCode);
typedef FilterInfoCallback = void Function(String addrFilter, String nameFilter);